

<template>
  <div class="part-spares-batch-form">
    <el-table v-table-style :data="form" :empty-text="$t('part.text27')">
      <el-table-column :label="$t('common.base.warehouse')" width="140px">
        <el-select v-model="scope.row.repertory" filterable slot-scope="scope" @input="chooseRepertory($event,scope.row)">
          <el-option v-for="(option, index) in repertory" :key="index + option.id" :label="option.name" :value="option.id"></el-option>
        </el-select>
      </el-table-column>
      <el-table-column :label="$t('common.base.name')" width="150px">
        <el-autocomplete
          slot-scope="scope"
          popper-class="batch-in-part"
          v-model="scope.row.sparepartName"
          :fetch-suggestions="selectPart(scope.row)"
          :placeholder="$t('task.tip.addPartTip1')"
          @select="choosePart($event, scope.row)">

          <div class="bacth-in-part-item" slot-scope="scope">
            <p>{{$t('common.base.name')}}：{{scope.item.sparepart&&scope.item.sparepart.name}}</p>
            <p>{{$t('common.label.serialNumber')}}：{{scope.item.sparepart&&scope.item.sparepart.serialNumber}}</p>
            <p>{{$t('common.part.specifications')}}：{{scope.item.sparepart&&scope.item.sparepart.standard}}</p>
            <p v-if="scope.item.sparepart.description">{{$t('common.label.explain')}}：{{scope.item.sparepart.description}}</p>
          </div>
        </el-autocomplete>

      </el-table-column>
      <el-table-column class-name="part-spares-serial-num" :label="$t('common.label.serialNumber')" prop="serialNumber" min-width="150px"></el-table-column>
      <el-table-column :label="$t('common.part.category')" prop="sparepartType" width="100px"></el-table-column>
      <el-table-column :label="$t('common.label.sparepartStandard')" prop="standard" width="100px"></el-table-column>
      <el-table-column :label="$t('common.label.type')" prop="type"></el-table-column>
      <el-table-column :label="$t('part.field9')" width="120px" min-width="80px">
        <template slot-scope="scope">
          {{scope.row.repertoryCount}}
          <el-tooltip v-if="scope.row.safetyStock && (Number(scope.row.safetyStock) > scope.row.repertoryCount)" class="item" effect="dark" :content="`${$t('part.text9')}：${scope.row.safetyStock}`" placement="top">
            <el-tag size="mini" type="danger" class="tag-position">{{ $t('part.components.partStock.text2') }}</el-tag>
          </el-tooltip>
        </template>
      </el-table-column>
      <!-- 目标库 -->
      <el-table-column :label="$t('part.field8')" width="160px" :placeholder="$t('part.tips29')">
        <template slot-scope="scope">
          <publink-select 
            v-if="scope.row.isFirst"
            v-model="scope.row.repertoryTarget" 
            @change="chooseSelect"
            :remote-method="(keyword) => getFetchUsers(keyword, scope.row.repertory)"
            filterable
            clearable
            remote
            is-search-user
            :loading="user.loading"
            :placeholder="$t('task.tip.applyMaterialTip2')"
            @visible-change="(visible) => visibleChange(visible, scope.row.repertory)"
          >

            <el-option v-for="(option, index) in repertorys" :origin="option" :key="index + option.userId" :label="option.displayName" :value="option.userId">
              <div class="srp-user-item">
                <img :src="option.head || '/resource/images/account_userhead.png'">
                <p>
                  <template v-if="isOpenData">
                    <open-data type="userName" :openid="option.staffId"></open-data>
                  </template>
                  <template v-else>
                    {{option.displayName}}
                  </template>
                </p>
              </div>
            </el-option>
            
            <!-- <template slot="multiple" slot-scope="{ item }">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="item.staffId"></open-data>
              </template>
              <template v-else>
                {{item.displayName}}
              </template>
            </template> -->
            
          </publink-select>
          
          <div v-else>
            <template v-if="isOpenData">
              <open-data type="userName" :openid="scope.row.repertoryStaffId"></open-data>
            </template>
            <template v-else>
              {{ scope.row.repertoryTarget }}
            </template>
          </div>
          
        </template>
      </el-table-column>
      <el-table-column :label="$t('part.field28')" prop="sparepartNumber"  width="120px"></el-table-column>

      <el-table-column :label="$t('part.text24')" width="80px">
        <el-input slot-scope="scope" v-model="scope.row.variation" type="number" step="any" :min="0" :max="parseInt(scope.row.repertoryCount)"></el-input>
      </el-table-column>
      <el-table-column :label="$t('common.label.operate')" width="60px" fixed="right">
        <el-button type="text" @click="remove(scope.row)" slot-scope="scope">{{ $t('common.base.delete') }}</el-button>
      </el-table-column>
    </el-table>

    <div class="in-stock-remark" v-if="form.length > 0">
      <el-input type='textarea' :maxlength="500" :placeholder="$t('common.paas.view.template.detail.placeholder1')" v-model="remark"></el-input>
    </div>
    
    <div class="part-batchIn-footer">
      <el-button type="text" @click="addPart" icon="el-icon-plus" :disabled="isAddBtnDisabled">{{ $t('common.base.add2') }}</el-button>
      <p v-if="isAddBtnDisabled">
        {{ $t('part.text30', {num:20}) }}
      </p>
    </div>
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform'
import MathUtil from '@src/util/math';
import { t } from '@src/locales'
import { getListByUserAndSparePartIds } from '@src/api/SparePart';

export default {
  name: 'part-spares-batch-form',
  inject: ['initData'],
  props: {
    sparepartConfig: Object,
    repertory: Array,
    repertories: {
      type: Array,
      default: () => []
    }
  },
  data(){
    return {
      isOpenData,
      repertorys: [],
      userId: '',
      user: {
        loading: false
      },
      repertoryTargetText: '',
      form: [],
      remark:'',
      userName: '',
      isAddBtnDisabled: false,
      personalLibraryUserId: '', // 目标库userId
      listByUserSparePartIds: [],
    }
  },
  computed: {
    // TODO: 支持小数 提示
    minVariation () {
      let initData = this.initData;
      return !initData || !initData.precision ? 1 : (initData.precision == 1 ? 0.1 : 0.01);
    },
    // 默认仓库
    defaultRepertoryId() {
      if (this.form.length) {
        console.log('this.for',this.form)
        return this.form[this.form.length - 1].repertory
      }
      return -1;
    },
    // 备件id集合
    sparepartIds() {
      return this.form.map(item => item.sparepart);
    }
  },
  methods: {
    /** 根据备件和人员查询个人库数量 */
    async getListByUserSparePartIdsReq(){
      try {
        const params = {
          userId: this.personalLibraryUserId,
          sparepartIds: this.sparepartIds
        }
        const res = await getListByUserAndSparePartIds(params);
        if(res.succ) {
          this.listByUserSparePartIds = res.data || [];
          this.initPersonalLibrary();
        }
      } catch(error){
        console.log(error)
      }
    },
    /** 个人库进行赋值 */
    initPersonalLibrary() {
      const sparePartMap = {};
      this.listByUserSparePartIds.forEach(ele => {
        sparePartMap[ele.sparepartId] = ele.sparepartNumber;
      });
      this.form.forEach(item => {
        const sparepartNumber = sparePartMap[item.sparepart] || 0;
        item.sparepartNumber = sparepartNumber;
        this.$set(item, 'sparepartNumber', sparepartNumber);
      });
    },
    chooseSelect(val) {
      let name = '';
      let staffId = ''
      this.personalLibraryUserId = ''
      
      this.repertorys.forEach(user => {
        if(user.userId == val) {
          name = user.displayName;
          staffId = user.staffId;
          this.personalLibraryUserId = user.userId;
        }
      })
      
      this.userName = name;
      this.form.forEach(item => {
        this.$set(item, 'repertoryTarget', name);
        this.$set(item, 'repertoryStaffId', staffId);
      })
      this.$set(this.form[0], 'repertoryTarget', val)

      if(this.personalLibraryUserId) {
        this.getListByUserSparePartIdsReq();
      }else {
        // 清除数据
        this.form.forEach(item => {
          item.sparepartNumber = '';
          this.$set(item, 'sparepartNumber', '');
        })
      }
    },
    remove(row){
      let index = -1;
      for(let i = 0; i < this.form.length; i++){
        if(this.form[i] == row){
          index = i;
          break;
        }
      }
      if(index >= 0) this.form.splice(index, 1);
      if(index == 0 && this.form.length > 0) {
        this.chooseSelect('');
        this.$set(this.form[0], 'isFirst', true);
        this.getFetchUsers();
      }
    },
    addPart() {
      if (this.form.length > 99) {
        this.isAddBtnDisabled = true;
        return this.$message({
          showClose: true,
          message: t('task.tip.addSparePartTip2', {max:100}),
          type: 'error'
        });
      }
      let row = this.add(null);
      if(!this.repertory.length){
        this.$platform.toast(t('part.text31'), 'warning');
        return;
      }
      this.form.push(row);
      if(this.form.length == 1) {
        this.getFetchUsers();
      }
    },
    add(event, row = {}){

      let repertories = this.repertory || [];
      // 默认仓库
      let defaultRepertory = repertories.filter((item => item.id == this.defaultRepertoryId))[0] || repertories[0] || ''
      
      let repertory = row.repertory || {};
      let sparepart = row.sparepart || {};

      let id = `${repertory.id }_${ sparepart.id}`;
      return {
        _id: id,
        sparepart: sparepart.id || '',
        sparepartName: sparepart.name || '',
        serialNumber: sparepart.serialNumber || '',
        sparepartType: sparepart.type || '',
        standard: sparepart.standard || '',
        type: '批量分配',
        repertory: repertory.id || defaultRepertory.id,
        repertoryTarget: this.userName || '',
        variation: 1,
        sparepartas: [],
        repertoryCount: row.repertoryCount || 0, // 库存数量
        safetyStock: row.safetyStock || '',
        sparepartNumber: row.sparepartNumber || 0, // 个人库存数量
      }
    },
    selectPart(row){
      let that = this
      return function(keyword, cb){
        that.fetchSparepart(keyword, cb, row)
      }
    },
    fetchSparepart(keyword, cb, row){
      row.sparepartName = keyword;
      if(!keyword) {
        row.sparepart = '';
      }
      let model = {
        keyWord: keyword,
        pageSize: 50,
        pageNum: 1,
        enable: 1,
        repertoryId: row.repertory,
        managers: [this.userId]
      }

      this.$http.post('/partV2/repertory/list', model)
        .then(result => cb(result.list))
        .catch(err => console.log(err))
    },
    visibleChange(visible, repertory) {
      if(visible) {
        this.repertorys = [];
        this.getFetchUsers('', repertory);
      }
    },
    getFetchUsers(keyword, repertory) {
      let params = {
        pageSize: 50,
        tagIds: [],
        keyword
      }
      // 分配个人库需要加上当前仓库对应的部门
      const currentRepertory = this.repertories?.find(item => item.id === repertory)
      params.tagIds = currentRepertory?.teamIds?.map(item => item.id) ?? []

      this.user.loading = true;

      this.$http.get('/partV2/repertory/users', params)
        .then(result => {
          let repertorys = result;
          if(this.form.length > 0 && !keyword) {
            this.$set(this.form[0], 'isFirst', true);
            // this.repertorys = repertorys;
          }
          // 需要把当前仓库的管理员添加进去
          (currentRepertory?.manager ?? [])?.forEach(item => {
            if(repertorys?.every(zItem => zItem.userId !== item.userId)) {
              repertorys.push(item)
            }
          })
          this.repertorys = repertorys;
        })
        .catch(err => console.warn(err))
        .finally(() => this.user.loading = false);
    },
    hasRow(value){
      return this.form.some(item => item._id == value)
    },
    async chooseRepertory(val, row) {
      row.sparepartName = '';
      row['_id'] = '';
      row.sparepart = '';
      row.sparepartName = '';
      row.serialNumber = '';
      row.sparepartType = '';
      row.standard = '';
      row.repertoryCount = '';
      row.safetyStock = '';
      row.repertory = val;
      row.sparepartNumber = '';
    },
    choosePart(value, row){
      let id = `${row.repertory }_${ value.sparepart.id}`;
      
      if(this.hasRow(id)) {
        this.$platform.toast(t('task.tip.chooseMaterialTip'), 'warning');
        row.sparepart = ''
        return
      }
      row['_id'] = id;
      row.sparepart = value.sparepart.id;
      row.sparepartName = value.sparepart.name;
      row.serialNumber = value.sparepart.serialNumber;
      row.sparepartType = value.sparepart.type;
      row.standard = value.sparepart.standard;
      row.repertoryCount = value.repertoryCount;
      row.safetyStock = value.safetyStock || null;
      this.getListByUserSparePartIdsReq()
    },
    async pack(){
      let form = this.form;
      try {
        let message = [];
        let msgStr = '';
        let repertorys = [];
        let firstRepertoryId = '';
        if(form.length > 0) {
          firstRepertoryId = form[0].repertory;
        }

        form.forEach((item, index) => {
          repertorys.push(item.repertory);
        })
        // 仓库 去重 
        let uniqueRepertorys = [...new Set(repertorys)];

        let ids = [];
        for(let j = 0; j < uniqueRepertorys.length; j++) {
          let repertory = uniqueRepertorys[j];
          for(let i = 0; i < this.repertories.length; i++) {
            let item = this.repertories[i];
            if(item.id == repertory) {
              ids.push(item.teamIds || []);
              break;
            }
          }
        }
        // 请求数据
        let requests = [];
        ids.forEach((item, index) => {
          if(Array.isArray(item)) {
            let tagIds = item.map(id => id.id);
            requests.push(this.fetchData(tagIds))
          }
        })
        let results = await Promise.all(requests);
        for(let r = 0; r < ids.length; ++r) {
          let users = JSON.parse(JSON.stringify(results[r]));
          if(users.some(item => item.userId == form[0].repertoryTarget)) {
            ids.splice(r, 1);
            results.splice(r, 1);
            --r
          }
        }
        let repertoriesIds = [];
        for(let a = 0; a < this.repertories.length; a++) {
          let rep = this.repertories[a];
          for(let b = 0; b < ids.length; b++) {
            let teamIds = ids[b];
            if(rep.teamIds == teamIds) {
              repertoriesIds.push(rep.id);
              break;
            }
          }
        }
        let bool = false;
        let initData = this.initData;
        form.forEach((item, index) => {
          // bool = false;
          let count = this.decimalNumber(item.variation);
          if(repertoriesIds.indexOf(item.repertory) > -1){
            // 判断是库的 管理员
            let users = [];
            for(let i = 0; i < this.repertories.length; i++) {
              let repertory = this.repertories[i];
              
              if(repertory.id == item.repertory) {
                users = repertory.manager;
                let isPartAdmin = users.some(user => user.userId == this.form[0].repertoryTarget);
                if(!isPartAdmin) {
                  message.push(t('part.text28', {num:index + 1}));
                  bool = true;
                  break;
                }
              }
            }
          }
          if( !item.sparepart 
              || !item.repertory 
              || !item.repertoryTarget 
              || item.variation <= 0 
              || item.repertoryCount == 0
              || count != -1){
            if(!bool) {
              msgStr = t('part.tips50');
              msgStr += initData.precision == 0 ? t('common.form.preview.materialOrder.tip6') : t('part.tips51', {num:initData.precision})
            }
          }
          if(item.variation > Number(item.repertoryCount)){
            if(!bool) {
              msgStr = t('part.text32');
            }
          }
        })
        msgStr ? message.push(msgStr) : '';
        if(message.length > 0){
          // 
          if(message.length > 4) {
            message = message.slice(0, 4);
            message[message.length - 1] += '...'
          }
          this.$platform.alert(message.join('\n'))
          return null;
        } 
        return form.map(item => ({
          sparepartId: item.sparepart,
          repertoryId: item.repertory,
          variation: item.variation,
          targetId: form[0].repertoryTarget,
          remark: this.remark
        }));
      } catch (error) {
        console.log(error)
      }
      return null;
    },
    fetchData(tagIds){
      let params = {
        pageSize: 0,
        tagIds
      }

      return this.$http.get('/partV2/repertory/users', params)
    },
    async remarkText() {
      return this.remark
    },
    receive(data = [], userId = ''){
      if (data.length > 20) {
        return this.$platform.alert(t('part.text29', {num:20}));
      }

      this.form = data.map(item => this.add(null, item));
      if(this.form.length >= 1) {
        this.getFetchUsers();
      }
      this.userId = userId;
    },
    decimalNumber(num) {
      let initData = this.initData;
      let count = MathUtil.decimalNumber(num);
      let isPartV2 = initData.isSparepart2;

      if(!isPartV2 && count != 0) return 0;
      if(initData.precision >= count) return -1;
      return initData.precision;
    }
  }
}
</script>

<style lang="scss">
.el-form-item{
  margin-bottom: 0
}

.part-batchIn-form{
  td,th{
    padding: 5px 0;
  }
  .cell {
    padding: 0 5px !important;
  }
}

.part-batchIn-footer{
  padding-top: 10px;
  text-align: center;
}

.batch-in-part{
  width: auto !important;
  max-width: 774px !important;
  li{
    padding: 5px;
    margin: 0 10px;
    border-bottom: 1px solid #f0f0f0;
    overflow: hidden;

    &:last-child{
      border-color: transparent;
    }
  }
}

.bacth-in-part-item{

  p{
    width:100%;
    overflow: hidden;
    white-space: initial;
    text-overflow: ellipsis;
    line-height: 24px;
    margin: 0;
  }
}
.in-stock-remark{
  width:100%;
  display:flex;
  margin:10px 0 0;
  padding:0 5px;
  textarea{
    flex:1;
    height:40px;
    min-height:40px;
    padding:10px;
    border-color:#dadada;
    &:focus{
      outline: none;
      border-color: $color-primary;
    }  
  }   
}

.part-spares-serial-num div{
  line-height: unset !important;
  height: auto !important;
  margin: 8px 0;
}
</style>